package com.yellowcong.demo;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintStream;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ConnectionInfo;
import ch.ethz.ssh2.Session;

/**
 * 创建日期:2018年1月11日<br/>
 * 创建时间:下午8:28:24<br/>
 * 创建者 :yellowcong<br/>
 * 机能概要:
 */
public class Demo2 {
	public static void main(String[] args) {

		try {
			String hostname = "192.168.100.10";
			String username = "root";
			String password = "yellowcong";

			Session session = null;
			Connection conn = null;

			System.out.println("connection 122 start...");

			// 建立连接
			conn = new Connection(hostname, 22);
			// 连接
			ConnectionInfo info = conn.connect();
			
			//授权
			boolean isAuthenticate = conn.authenticateWithPassword(username, password);
			if(isAuthenticate){
				
				//打开连接
				session = conn.openSession();
				//打开bash
				session.requestPTY("bash");
//				session.requestPTY("xterm", 90, 30, 0, 0, null);
				
				session.startShell();
				
				//启动多线程，来获取我们运行的结果
				//第一个参数  输入流
				//第二个参数  输出流，这个直接输出的是控制台
				ReadThread is = new ReadThread(session.getStdout(), new PrintStream(System.out));
				new Thread(is).start();
				
				//启动线程2，我
				ReadThread error = new ReadThread(session.getStderr(), new PrintStream(System.out));
				new Thread(error).start();
				
				// 输出流
				BufferedWriter out = new BufferedWriter(new OutputStreamWriter(session.getStdin(), "utf-8"));
				out.write("ls\n");
				out.flush();
				
				//输入命令
				out.write("ifconfig\n");
				out.flush();
				
				//输出命令
				out.write("ip addr\n");
				out.flush();
				
				//清空
				out.write("clear\n");
				out.flush();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
